package cn.ruanyun.backInterface.modules.business.profitDetail.serviceimpl;

import cn.ruanyun.backInterface.base.RuanyunBaseEntity;
import cn.ruanyun.backInterface.common.enums.ProfitDetailEnum;
import cn.ruanyun.backInterface.modules.base.pojo.User;
import cn.ruanyun.backInterface.modules.base.service.mybatis.IUserService;
import cn.ruanyun.backInterface.modules.business.order.service.IOrderService;
import cn.ruanyun.backInterface.modules.business.profitDetail.dto.ProfitDetailDto;
import cn.ruanyun.backInterface.modules.business.profitDetail.mapper.ProfitDetailMapper;
import cn.ruanyun.backInterface.modules.business.profitDetail.pojo.ProfitDetail;
import cn.ruanyun.backInterface.modules.business.profitDetail.service.IProfitDetailService;
import cn.ruanyun.backInterface.modules.business.profitDetail.vo.ProfitDetailCount;
import cn.ruanyun.backInterface.modules.business.profitDetail.vo.ProfitDetailVo;
import cn.ruanyun.backInterface.modules.business.storeIncome.pojo.StoreIncome;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.ruanyun.backInterface.common.utils.ToolUtil;


/**
 * 分红明细接口实现
 * @author z
 */
@Slf4j
@Service
@Transactional
public class IProfitDetailServiceImpl extends ServiceImpl<ProfitDetailMapper, ProfitDetail> implements IProfitDetailService {


    @Autowired
    private IUserService userService;

    @Autowired
    private IOrderService orderService;



    @Override
    public List<ProfitDetailVo> getProfitDetailList(ProfitDetailDto profitDetailDto) {

        List<String> userIds = new ArrayList<>();

        if (ToolUtil.isNotEmpty(profitDetailDto.getNickName()) || ToolUtil.isNotEmpty(profitDetailDto.getMobile())){

            userIds = userService.list(Wrappers.<User>lambdaQuery()
                    .like(ToolUtil.isNotEmpty(profitDetailDto.getNickName()),User::getNickName, profitDetailDto.getNickName())
                    .like(ToolUtil.isNotEmpty(profitDetailDto.getMobile()),User::getMobile, profitDetailDto.getMobile())
            ).parallelStream().map(RuanyunBaseEntity::getId).collect(Collectors.toList());
        }

        boolean isAdmin = false;

        if ("平台".equals(profitDetailDto.getNickName())){
            userIds = null;
            isAdmin = true;
        }

        return Optional.ofNullable(ToolUtil.setListToNul(this.list(Wrappers.<ProfitDetail>lambdaQuery()
                .in(ToolUtil.isNotEmpty(userIds),ProfitDetail::getCreateBy,userIds)
                .isNull(isAdmin,ProfitDetail::getCreateBy)
        .orderByDesc(ProfitDetail::getCreateTime))))
        .map(profitDetails -> profitDetails.parallelStream().flatMap(profitDetail -> {


            ProfitDetailVo profitDetailVo = new ProfitDetailVo();

            //平台信息
            if (ToolUtil.isEmpty(profitDetail.getCreateBy())) {

                profitDetailVo.setNickName("平台");
            }

            //用户信息
            Optional.ofNullable(userService.getById(profitDetail.getCreateBy()))
                    .ifPresent(user -> {

                        ToolUtil.copyProperties(user, profitDetailVo);
                    });

            //订单信息
            Optional.ofNullable(orderService.getById(profitDetail.getOrderId()))
                    .ifPresent(order -> {

                        ToolUtil.copyProperties(order, profitDetailVo);

                        //分账金额信息
                        profitDetailVo.setProfitTotalMoney(order.getTotalPrice())
                                .setProfitMoney(profitDetail.getProfitMoney());

                    });

            ToolUtil.copyProperties(profitDetail, profitDetailVo);

            return Stream.of(profitDetailVo);
        }).collect(Collectors.toList())).orElse(null);



    }

    @Override
    public ProfitDetailCount getProfitDetailVo() {


        return Optional.ofNullable(ToolUtil.setListToNul(this.list(Wrappers.<ProfitDetail>lambdaQuery()
                .eq(ProfitDetail::getProfitDetailEnum, ProfitDetailEnum.PLATFORM))))
                .map(profitDetails -> {

                    ProfitDetailCount profitDetailCount = new ProfitDetailCount();

                    //日收入
                    BigDecimal dayIncome = profitDetails.parallelStream().filter(profitDetail ->
                            getDay(profitDetail.getCreateTime()).equals(getDay(new Date())))
                            .map(ProfitDetail::getProfitMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

                    //月收入
                    BigDecimal monthIncome = profitDetails.parallelStream().filter(profitDetail ->
                            getMonth(profitDetail.getCreateTime()).equals(getMonth(new Date())))
                            .map(ProfitDetail::getProfitMoney).reduce(BigDecimal.ZERO, BigDecimal::add);


                    //年收入
                    BigDecimal yearIncome = profitDetails.parallelStream().filter(profitDetail ->
                            getYear(profitDetail.getCreateTime()).equals(getYear(new Date())))
                            .map(ProfitDetail::getProfitMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

                    //总收入
                    BigDecimal totalIncome = profitDetails.parallelStream().map(ProfitDetail::getProfitMoney)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                    profitDetailCount.setDayIncome(dayIncome).setMonthIncome(monthIncome)
                            .setYearIncome(yearIncome).setTotalIncome(totalIncome);

                    return profitDetailCount;

                }).orElse(new ProfitDetailCount());

    }

    /**
     * 獲取当前天
     * @param date  date
     * @return Integer
     */
    public Integer getDay(Date date) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DATE);
    }


    /**
     * 獲取当前月
     * @param date date
     * @return Integer
     */
    public Integer getMonth(Date date) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH);
    }

    /**
     * 獲取当前年
     * @param date date
     * @return Integer
     */
    public Integer getYear(Date date) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }

}